package com.example.mybatistest.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.type.TypeHandlerRegistry;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@Slf4j
@Intercepts({
        @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}),
        @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})
})
public class H_SqlFormatInterceptor implements Interceptor {
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        try {
            Object[] queryArgs = invocation.getArgs();
            MappedStatement mappedStatement = (MappedStatement) queryArgs[0];

            // 获取SQL
            BoundSql boundSql = mappedStatement.getBoundSql(queryArgs[1]);
            long startTime = System.currentTimeMillis();
            Configuration configuration = mappedStatement.getConfiguration();
            long endTime = System.currentTimeMillis();
            long time = endTime - startTime;
            printSqlLog(configuration, boundSql, time);
        } catch (Exception e) {
            log.error("===> HH-SQL-FORMAT: SQL Format Intercept Error.");
        }

        return invocation.proceed();

    }

    public static void printSqlLog(Configuration configuration, BoundSql boundSql, long time) {
        Object parameterObject = boundSql.getParameterObject();
        List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
        String sql = boundSql.getSql().replaceAll("[\\s]+", " ");
        if (parameterMappings.size() > 0 && parameterObject != null) {
            TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();
            if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
                sql = sql.replaceFirst("\\?", parameterObject.toString());
            } else {
                MetaObject metaObject = configuration.newMetaObject(parameterObject);
                for (ParameterMapping parameterMapping : parameterMappings) {
                    String propertyName = parameterMapping.getProperty();
                    Object obj;
                    if (metaObject.hasGetter(propertyName)) {
                        obj = metaObject.getValue(propertyName);
                    } else if (boundSql.hasAdditionalParameter(propertyName)) {
                        obj = boundSql.getAdditionalParameter(propertyName);
                    } else {
                        obj = "缺值";
                    }
                    sql = sql.replaceFirst("\\?", addCama(obj));
                }
            }
        }
        log.error("===> HH-SQL-FORMAT: " + sql);
        log.error("===> HH-SQL-FORMAT TIME:" + time + " ms");
    }

    private static String addCama(Object target) {

        if (Optional.ofNullable(target).isEmpty()) {
            return "null";
        }
        if (target instanceof String) {
            return "'" + target + "'";
        }

        if (target instanceof Date) {
            SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
            return formatter.format((Date) target);
        }
        return target.toString();
    }
}
